package com.tencent.wuyanzu.whattoeat.util;

/**
 * Created by bleuesprit on 2016/7/24.
 */

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 对imageView进行异步加载图片。图片请求成功直接更改BitMap
 * 输入参数第一个是url，第二个是Bitmap数组。用数组因为如果单独传变量，那么这里没法改变传进来的东西。
 * BitmapLoadURL downloadBitmapAsyncTask = new BitmapLoadURL();

   downloadBitmapAsyncTask.execute(imageUrl,myImageView);
 */



public class BitmapLoadURL extends AsyncTask<Object, Void, Bitmap> {
    private String imageUrl;
    private Bitmap mBitmap[];
    @Override
    protected Bitmap doInBackground(Object... params) {
        imageUrl = (String) params[0];
        mBitmap=(Bitmap[]) params[1];
        Bitmap bitmap = downloadBitmap((String)params[0]);
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        //下载完成后,找到其对应的ImageView显示图片

            mBitmap[0]=bitmap;

    }


    // 获取Bitmap
    private Bitmap downloadBitmap(String imageUrl) {
        Bitmap bitmap = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(imageUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();

            httpURLConnection.setConnectTimeout(5 * 1000);
            httpURLConnection.setReadTimeout(10 * 1000);
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();
            httpURLConnection.getResponseMessage();
            Log.d("BitmapLoadURL","httpURL state"+httpURLConnection.getResponseMessage());
            InputStream inputStream=httpURLConnection.getInputStream();
            //byte []buffer=new byte[10];
            // inputStream.read(buffer);
            if(inputStream==null)
            {
                Log.d("BitmapLoadURL","inputis nullll");
            }
            bitmap = BitmapFactory.decodeStream(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return bitmap;
    }
}




